from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.db import connection

def todos(request):
    if request.method == 'POST':
        # 执行添加的逻辑（1.接收待办事项标题，2执行添加sql语句）
        title=request.POST.get('title')
        with connection.cursor() as cursor:
            result=cursor.execute('insert into restful_todo values(null,"{}",1)'.format(title))
            if result:
                return redirect('/todolist')
    else:
        with connection.cursor() as cursor:
            cursor.execute('select * from restful_todo order by id desc')
            data=cursor.fetchall()
        return render(request, 'todolist.html', {'todolist':data})
def todo_del(request):
    id=request.GET.get('id')
    with connection.cursor() as cursor:
        result = cursor.execute('delete from restful_todo where id={}'.format(id))
        if result:
            return redirect('/todolist')
def todo_edit_status(request):
    id = request.GET.get('id')
    with connection.cursor() as cursor:
        cursor.execute('select * from restful_todo where id={}'.format(id))
        row = cursor.fetchone()
        #假设 这条记录的原来的done字段值为 0
        done=1
        #如果假设不成立
        if row[2]==1:
            done=0
        result=cursor.execute('update restful_todo set done={} where id={}'.format(done,id))
        if result:
            return redirect('/todolist')


